package com.example.controller;

import com.example.config.Utils.FileUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 下载上传文件的模板
 *
 * @author: liu
 * 2022-03-20-10:03
 **/
@Api(tags = "DownloadController")
@RestController
public class DownloadController {

    @ApiOperation(value = "下载模板")
    @GetMapping(value = "/downloadTemplate")
    public void downloadTemplate(HttpServletResponse response) throws IOException{
//        String fileName = "xxxFile.xlsx";
//        ClassPathResource resource = new ClassPathResource(fileName);
//        InputStream stream = resource.getInputStream();


//        // 以流的形式下载文件。
//        try {
//            //读取文件
//            InputStream resourceAsStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("MyFile/药品信息入库清单模板.xlsx");
//            System.out.println("resourceAsStream is "+resourceAsStream);
//            InputStream fis = new BufferedInputStream(resourceAsStream);
//            byte[] buffer = new byte[fis.available()];
//            fis.read(buffer);
//            fis.close();
//            // 清空response
//            response.reset();
//            // 设置response的Header
//            response.setHeader("Content-Disposition", "attachment;filename="+java.net.URLEncoder.encode("药品信息入库清单模板.xlsx", "utf-8"));
//            //response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
//            response.addHeader("Content-Length", "" + buffer.length);
//            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
//            response.setContentType("application/octet-stream");
//            toClient.write(buffer);
//            toClient.flush();
//            toClient.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String fileName = "药品信息入库清单模板";
//        response.setHeader("Content-disposition","attachment;filename="+new String(fileName.getBytes(StandardCharsets.UTF_8)));
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        try {
//            InputStream inputStream = FileUtil.getResourcesFileInputStream("MyFile/药品信息入库清单模板.xlsx");
//            System.out.println(inputStream);
//            OutputStream outputStream = response.getOutputStream();
//            byte[] b = new byte[2048];
//            int len;
//            while ((len = inputStream.read(b)) != -1){
//                outputStream.write(b,0,len);
//            }
//        } catch (IOException e){
//            e.printStackTrace();
//        }
//        String fileName = URLEncoder.encode("药品信息入库清单模板", "UTF-8");
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), StandardCharsets.ISO_8859_1));
////        response.setContentType("application/octet-stream; charset=UTF-8");
//        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        Resource[] resources = resolver.getResources("MyFile/药品信息入库清单模板.xlsx");
//        Resource resource = resources[0];
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        InputStream stream = resource.getInputStream();
////        StringBuilder buffer = new StringBuilder();
//        byte[] bytes = new byte[1024];
//        int len = 0;
//        try {
//            while ((len = stream.read(bytes)) != -1) {
//                response.getOutputStream().write(bytes, 0, len);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }



        try {
            // 以流的形式下载文件   这种方法，打成jar包之后，下载的文件，会被损坏    注意  template  前没有斜杠
            InputStream fis = FileUtil.getResourcesFileInputStream("MyFile/药品信息入库清单模板.xlsx");
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode("药品信息入库清单模板", "UTF-8") + ".xlsx");
            //response.setContentType("application/zip");
            response.setContentType("application/binary;charset=ISO8859-1");
            ServletOutputStream out = response.getOutputStream();
            out.write(buffer);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        response.setContentType("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//        response.setHeader("Content-Disposition",
//                "attachment;filename=" + URLEncoder.encode("药品信息入库清单模板", "UTF-8") + ".xlsx");
//        response.setHeader("Access-Control-Expose-Headers", "Content-disposition");
//        String filename1 = "药品信息入库清单模板";
//        response.reset();
//        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename1.getBytes(), StandardCharsets.ISO_8859_1));
//        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//        response.setHeader("Pragma", "no-cache");
//        response.setHeader("Cache-Control", "no-cache");
//        response.setDateHeader("Expires", 0);
//        try {
//            Resource resource = new ClassPathResource("MyFile/设备导入模板.xlsx");   //静态文件位置
//            InputStream inputStream = resource.getInputStream();
//            byte[] buffer = new byte[inputStream.available()];   //问题所在
//            inputStream.read(buffer);
//            inputStream.close();
//            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//            outputStream.write(buffer);
//            outputStream.flush();
//            outputStream.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//            response.setStatus(404);
//        }
//        try {
//            //注意  template  前没有斜杠
//            InputStream fis = FileUtil.getResourcesFileInputStream("MyFile/药品信息入库清单模板.xlsx");
//            byte[] buffer = new byte[fis.available()];
//            fis.read(buffer);
//            fis.close();
//            response.setContentType("application/binary;charset=ISO8859-1");
//            String fileName = java.net.URLEncoder.encode("药品信息入库清单模板", "UTF-8");
//            response.setHeader("Content-disposition", "attachment; filename=" + fileName + ".xlsx");
////            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
//            response.setHeader("Pragma", "no-cache");
//            response.setHeader("Cache-Control", "no-cache");
//            response.setDateHeader("Expires", 0);
//            ServletOutputStream out = null;
//            out = response.getOutputStream();
//            out.write(buffer);
//            out.flush();
//            out.close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            //关闭文件输出流
//        }

        /*String path = "";
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resolver.getResources("MyFile/药品信息入库清单模板.xlsx");
        Resource resource = resources[0];
//        path = resource.getFile().getPath();
//        //创建文件对象，传递路径参数
//        File file = new File(path);
        //获取文件名
        String filename1 = "药品信息入库清单模板.xlsx";
        //获得文件流，因为在jar文件中，不能直接通过文件资源路径拿到文件，但是可以在jar包中拿到文件流
        InputStream stream = resource.getInputStream();
        /*StringBuilder buffer = new StringBuilder();
        byte[] bytes = new byte[1024];
        try {
            for (int n; (n = stream.read(bytes)) != -1; ) {
                buffer.append(new String(bytes, 0, n));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        txt = buffer.toString();*/
        /*response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename1.getBytes(), StandardCharsets.ISO_8859_1));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try (OutputStream out = response.getOutputStream();
             BufferedInputStream bis = new BufferedInputStream(stream)) {
            byte[] buff = new byte[1024];
            int i = bis.read(buff);
            while (i != -1) {
                out.write(buff, 0, buff.length);
                out.flush();
                i = bis.read(buff);
            }
        }*/


        /*Resource resource = new ClassPathResource("MyFile/药品信息入库清单模板.xlsx");
        String path = "";
//        path = System.getProperty("user.dir")+ "/src/main/resources/MyFile/药品信息入库清单模板.xlsx";
        path = resource.getFile().getPath();
        //创建文件对象，传递路径参数
        File file = new File(path);
        //获取文件名
        String filename1 = file.getName();
        //创建缓冲流
//        InputStream fis = new BufferedInputStream(new FileInputStream("/"+path));
//        InputStream fis = new BufferedInputStream(new FileInputStream(path));
        InputStream fis =getClass().getClassLoader().getResourceAsStream(path);
        /*byte[] buffer = new byte[fis.available()];
        //读操作
        fis.read(buffer);
        //关流
        fis.close();*/
        //设置响应信息 (响应编码等)
        /*response.reset();
        response.setHeader("Content-Disposition", "attachment;filename=" + new String(filename1.getBytes(), "iso-8859-1"));
        response.setContentType("application/vnd.ms-excel;charset=UTF-8");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        try (OutputStream out = response.getOutputStream();
             BufferedInputStream bis = new BufferedInputStream(fis)) {
            byte[] buff = new byte[1024];
            int i = bis.read(buff);
            while (i != -1) {
                out.write(buff, 0, buff.length);
                out.flush();
                i = bis.read(buff);
            }
        }
        */
        /*//响应输出流
        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
        //写操作
        toClient.write(buffer);
        //刷新
        toClient.flush();
        //关流
        toClient.close();*/

//        String fileName = "";
//        String sheetName = "";
//        String type = ".xlsx";
//        // 这里注意 有同学反应使用swagger 会导致各种问题，请直接用浏览器或者用postman
//        response.setContentType("application/vnd.ms-excel");
//        response.setCharacterEncoding("utf-8");
//
//        List<MI_Table> medicineInfoList = new ArrayList<>();
//        MI_Table medicineInfo = new MI_Table();
//
//        medicineInfo.setMId(1);
//        medicineInfo.setMName("阿昔洛韦乳膏");
//        medicineInfo.setMSpecification("10g");
//        medicineInfo.setMManufacturer("湖南五洲通药业股份有限公司");
//        medicineInfo.setMMajorfunction("用于单纯疱疹或带状疱疹感染");
//        medicineInfo.setMAdversereaction("......");
//        medicineInfo.setMTaboos("小孩、孕妇禁用");
//        medicineInfo.setMValiduntil("2023-12-01");
//        medicineInfo.setMKinds("皮肤科用药类");
//        medicineInfo.setMBatchnum(210103);
//        medicineInfo.setMApprovalnum("国药准字H20066173");
//        medicineInfo.setMOtc("非处方药");
//
//        medicineInfoList.add(medicineInfo);
//        System.out.println(medicineInfoList);
//
//        fileName = "药品信息入库清单模板";
//        sheetName = "药品信息入库清单模板";
//
//        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
//        fileName = URLEncoder.encode(fileName, "UTF-8");
//        java.net.URLDecoder.decode(fileName, "UTF-8");
//        response.setHeader("Content-disposition", "attachment;filename=" + fileName + type);
//        EasyExcel.write(response.getOutputStream(), MI_Table.class).sheet(sheetName).doWrite(medicineInfoList);

    }

}
